/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.infor.web;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

import com.jeeplus.modules.ap.entity.Expenditure;
import com.jeeplus.modules.ap.entity.Fine;
import com.jeeplus.modules.ap.service.ExpenditureService;
import com.jeeplus.modules.ap.service.FineService;
import com.jeeplus.modules.fee.entity.Profit;
import com.jeeplus.modules.fee.service.ProfitService;
import com.jeeplus.modules.fleet.entity.Budget;
import com.jeeplus.modules.fleet.entity.WagesDetil;
import com.jeeplus.modules.fleet.service.WagesDetilService;
import com.jeeplus.modules.infor.entity.*;
import com.jeeplus.modules.infor.service.*;
import com.jeeplus.modules.sys.utils.UserUtils;
import com.jeeplus.modules.wms.entity.WorkStatistics;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;

/**
 * 利润分析总表Controller
 * @author 李超辉
 * @version 2018-09-26
 */
@Controller
@RequestMapping(value = "${adminPath}/infor/profitAnalysis")
public class ProfitAnalysisController extends BaseController {

	@Autowired
	private ProfitAnalysisService profitAnalysisService;
	@Autowired
	private JdbcTemplate jdbc;
	@Autowired
	private ProfitService profitService;
	@Autowired
	private RentDetilService rentPriceService;
	@Autowired
	private PositionService positionService;
	@Autowired
	private LoadingBottomService loadingBottomService;
	@Autowired
	private LoadingIncomeService loadingIncomeService;
	@Autowired
	private LoadingOutService loadingOutService;
	@Autowired
	private LoadDetilService loadDetilService;
	@Autowired
	private ExpenditureService expenditureService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private WagesDetilService wagesDetilService;
	@Autowired
	private FineService fineService;
	@Autowired
	private StoreBudgetService storeBudgetService;
	@Autowired
	private HandlingService handlingService;
	
	@ModelAttribute
	public ProfitAnalysis get(@RequestParam(required=false) String id) {
		ProfitAnalysis entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = profitAnalysisService.get(id);
		}
		if (entity == null){
			entity = new ProfitAnalysis();
		}
		return entity;
	}
	
	/**
	 * 利润分析总表列表页面
	 */
	@RequiresPermissions("infor:profitAnalysis:list")
	@RequestMapping(value = {"list", ""})
	public String list() {
		return "modules/infor/profitAnalysisList";
	}
	/**
	 * 利润分析总表列表页面
	 */
	@RequiresPermissions("infor:profitAnalysis:list")
	@RequestMapping(value = {"list1"})
	public String list1() {
		return "modules/infor/1/profitAnalysisList";
	}
	/**
	 * 利润分析总表列表页面
	 */
	@RequiresPermissions("infor:profitAnalysis:list")
	@RequestMapping(value = {"list2"})
	public String list2() {
		return "modules/infor/2/profitAnalysisList";
	}
	/**
	 * 利润分析总表列表页面
	 */
	@RequiresPermissions("infor:profitAnalysis:list")
	@RequestMapping(value = {"list3"})
	public String list3() {
		return "modules/infor/3/profitAnalysisList";
	}

	/**
	 * 利润分析总表列表数据
	 */
	@ResponseBody
	@RequestMapping(value = "cx")
	public String cx(Date min, Date max, String pro) {
		if(min==null||max==null){
			return "false";
		}
       jdbc.execute("delete from infor_profit_analysis");
		Calendar c = Calendar.getInstance();
		DecimalFormat df = new DecimalFormat("0.00%");
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		NumberFormat nf = NumberFormat.getInstance();
		Date i=min;
        Date mixx;
        Date maxx;
		while (i.getTime()<max.getTime()) {
			mixx=i;
			ProfitAnalysis p=new ProfitAnalysis();
			p.setDate(i);
			c.setTime(i);
			c.add(Calendar.MONTH, 1);
			i=c.getTime();
			maxx=i;
			//运输利润
			Profit profit=new Profit();
			profit.setMin(format.format(mixx));
			profit.setMax(format.format(maxx));
			//仓租
			StoreBudget s=new StoreBudget();
			s.setRq(mixx);
			//装卸收入
			Handling h=new Handling();
			h.setDate(mixx);

           //管理成本
			Expenditure e=new Expenditure();
			e.setMinDate(format.format(mixx));
			e.setMax(format.format(maxx));
			Fine fine=new Fine();
			fine.setDate(mixx);
			if(pro!=null &&!pro.equals("")&&!pro.equals("undefined")){
				profit.setPro(pro);
				s.setPro(pro);
				h.setPro(pro);
				fine.setPro(pro);
				e.setProjectName(projectService.findUniqueByProperty("name",pro));
			}else if(!UserUtils.getUseroffice().equals("总部")){
				profit.setPro(UserUtils.getUseroffice());
				s.setPro(UserUtils.getUseroffice());
				h.setPro(UserUtils.getUseroffice());
				fine.setPro(UserUtils.getUseroffice());
				e.setProjectName(projectService.findUniqueByProperty("name",UserUtils.getUseroffice()));
			}
			List<Expenditure> exs=expenditureService.findList(e);
			Double gl=0.0;
			for(Expenditure ex:exs){
				gl+=ex.getMoney();
			}
			p.setRemarks(nf.format(gl).replaceAll(",",""));
			List<Handling> loads=handlingService.findList(h);

           double zxzc=0.0;
           double zxsr=0.0;
           double ysfk=0.0;
           double czfk=0.0;
           double zxfk=0.0;
           for(Handling lo:loads){
           	zxfk+=Double.parseDouble(lo.getFk());
           	zxzc+=Double.parseDouble(lo.getZzc());
           	zxsr+=Double.parseDouble(lo.getZsr());
		   }
			p.setZxzc(nf.format(zxzc).replaceAll(",",""));
            p.setZxsr(nf.format(zxsr).replaceAll(",",""));
			p.setZxfk(nf.format(zxfk).replaceAll(",",""));

            List<StoreBudget> lis=storeBudgetService.findList(s);
			Double zsr1=0.0;
			Double zzc1=0.0;
			for(StoreBudget ren:lis){
					zsr1+=Double.parseDouble(ren.getZsr());
					zzc1+=Double.parseDouble(ren.getZzc());
					czfk+=Double.parseDouble(ren.getFk());
			}
			p.setCzsr(nf.format(zsr1).replaceAll(",",""));
			p.setCzzc(nf.format(zzc1).replaceAll(",",""));
			p.setCzfk(nf.format(czfk).replaceAll(",",""));

			fine.setRemarks("已确认");
			fine.setJf(1);
			fine.setType("现场管理");
			List<Fine> fines=fineService.findList(fine);
			for(Fine fi:fines){
				ysfk+=Double.parseDouble(fi.getZxje());
			}
			fine.setType("未上车");
			List<Fine> fines1=fineService.findList(fine);
			for(Fine fi:fines1){
				ysfk+=Double.parseDouble(fi.getZxje());
			}
			fine.setType("延迟送达");
			List<Fine> fines2=fineService.findList(fine);
			for(Fine fi:fines2){
				ysfk+=Double.parseDouble(fi.getZxje());
			}
			p.setYsfk(nf.format(ysfk).replaceAll(",",""));

			List<Profit> list=profitService.findList(profit);
			Double zsr=0.0;
			Double zzc=0.0;
			Double zsj=0.0;
			for(Profit pr:list){
				zsr+=Double.parseDouble(pr.getSr());
				zzc+=Double.parseDouble(pr.getZzc());
				zsj+=Double.parseDouble(pr.getSj());
			}
			p.setSj(nf.format(zsj).replaceAll(",",""));
            p.setYssr(nf.format(zsr).replaceAll(",",""));
            p.setYszc(nf.format(zzc).replaceAll(",",""));

            //总额
			double zzsr=zsr+zsr1+zxsr;
            double zzzc=zzc+zzc1+zxzc;
            double mlr=zzsr-zzzc-gl;
            double lrl=mlr/zzsr;
            p.setZsr(nf.format(zzsr).replaceAll(",",""));
            p.setZzc(nf.format(zzzc).replaceAll(",",""));
            p.setMlr(nf.format(mlr).replaceAll(",",""));
            p.setLrl(df.format(lrl));
			profitAnalysisService.save(p);
		}
		return "success";
	}
	public List<Map<String,Object>> rk(String min,String pro){
		String sql;

		if(!pro.equals("总部")){
			sql = "SELECT p.pro as pro, p.position AS position,p.name as name,p.gtype AS gtype,SUM(p.workload) AS amount FROM `wms_statistics` p WHERE   DATE_FORMAT('"+min+"','%Y%m')=DATE_FORMAT(p.create_date,'%Y%m')  and p.pro='" + pro + "'   GROUP BY p.pro,p.name, p.position,p.gtype";
		}else{
			sql = "SELECT p.pro as pro, p.position AS position,p.name as name, p.type AS type,p.gtype AS gtype,SUM(p.workload) AS amount FROM `wms_statistics` p WHERE DATE_FORMAT('"+min+"','%Y%m')=DATE_FORMAT(p.create_date,'%Y%m')  GROUP BY p.name,p.position,p.gtype ";
		}
		List<Map<String,Object>> list=jdbc.queryForList(sql);
		return  list;
	}
	public List<Map<String,Object>> ck(String min,String pro){
		String sq;
		if(!pro.equals("总部")){
			sq = "SELECT p.pro as pro, p.position AS position,p.name as name, p.gtype AS gtype,SUM(p.work) AS amount FROM `wms_outstatistics` p WHERE DATE_FORMAT('"+min+"','%Y%m')=DATE_FORMAT(p.create_date,'%Y%m') and p.pro='" + pro + "'   GROUP BY  p.pro,p.name, p.position,p.gtype";
		}else{
			sq = "SELECT p.pro as pro, p.position AS position,p.name as name, p.type AS type,p.gtype AS gtype,SUM(p.work) AS amount FROM `wms_outstatistics` p WHERE DATE_FORMAT('"+min+"','%Y%m')=DATE_FORMAT(p.create_date,'%Y%m'))  GROUP BY p.name,p.p.position,p.gtype";
		}
		List<Map<String,Object>> lis=jdbc.queryForList(sq);
		return  lis;
	}


		/**
	 * 利润分析总表列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:profitAnalysis:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(ProfitAnalysis profitAnalysis, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ProfitAnalysis> page = profitAnalysisService.findPage(new Page<ProfitAnalysis>(request, response), profitAnalysis);
		return getBootstrapData(page);
	}
	/**
	 * 利润分析总表列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:profitAnalysis:list")
	@RequestMapping(value = "data1")
	public Map<String, Object> data1(ProfitAnalysis profitAnalysis, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ProfitAnalysis> page = profitAnalysisService.findPage1(new Page<ProfitAnalysis>(request, response), profitAnalysis);
		return getBootstrapData(page);
	}
	/**
	 * 利润分析总表列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:profitAnalysis:list")
	@RequestMapping(value = "data2")
	public Map<String, Object> data2(ProfitAnalysis profitAnalysis, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ProfitAnalysis> page = profitAnalysisService.findPage2(new Page<ProfitAnalysis>(request, response), profitAnalysis);
		return getBootstrapData(page);
	}
	/**
	 * 利润分析总表列表数据
	 */
	@ResponseBody
	@RequiresPermissions("infor:profitAnalysis:list")
	@RequestMapping(value = "data3")
	public Map<String, Object> data3(ProfitAnalysis profitAnalysis, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<ProfitAnalysis> page = profitAnalysisService.findPage3(new Page<ProfitAnalysis>(request, response), profitAnalysis);
		return getBootstrapData(page);
	}
	/**
	 * 查看，增加，编辑利润分析总表表单页面
	 */
	@RequiresPermissions(value={"infor:profitAnalysis:view","infor:profitAnalysis:add","infor:profitAnalysis:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(ProfitAnalysis profitAnalysis, Model model) {
		model.addAttribute("profitAnalysis", profitAnalysis);
		return "modules/infor/profitAnalysisForm";
	}

	/**
	 * 保存利润分析总表
	 */
	@ResponseBody
	@RequiresPermissions(value={"infor:profitAnalysis:add","infor:profitAnalysis:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public AjaxJson save(ProfitAnalysis profitAnalysis, Model model, RedirectAttributes redirectAttributes) throws Exception{
		AjaxJson j = new AjaxJson();
		if (!beanValidator(model, profitAnalysis)){
			j.setSuccess(false);
			j.setMsg("非法参数！");
			return j;
		}
		profitAnalysisService.save(profitAnalysis);//新建或者编辑保存
		j.setSuccess(true);
		j.setMsg("保存利润分析总表成功");
		return j;
	}
	
	/**
	 * 删除利润分析总表
	 */
	@ResponseBody
	@RequiresPermissions("infor:profitAnalysis:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(ProfitAnalysis profitAnalysis, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		profitAnalysisService.delete(profitAnalysis);
		j.setMsg("删除利润分析总表成功");
		return j;
	}
	
	/**
	 * 批量删除利润分析总表
	 */
	@ResponseBody
	@RequiresPermissions("infor:profitAnalysis:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			profitAnalysisService.delete(profitAnalysisService.get(id));
		}
		j.setMsg("删除利润分析总表成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("infor:profitAnalysis:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(ProfitAnalysis profitAnalysis, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "利润分析总表"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<ProfitAnalysis> page = profitAnalysisService.findPage(new Page<ProfitAnalysis>(request, response, -1), profitAnalysis);
    		new ExportExcel("利润分析总表", ProfitAnalysis.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出利润分析总表记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("infor:profitAnalysis:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<ProfitAnalysis> list = ei.getDataList(ProfitAnalysis.class);
			for (ProfitAnalysis profitAnalysis : list){
				try{
					profitAnalysisService.save(profitAnalysis);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条利润分析总表记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条利润分析总表记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入利润分析总表失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/profitAnalysis/?repage";
    }
	
	/**
	 * 下载导入利润分析总表数据模板
	 */
	@RequiresPermissions("infor:profitAnalysis:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "利润分析总表数据导入模板.xlsx";
    		List<ProfitAnalysis> list = Lists.newArrayList(); 
    		new ExportExcel("利润分析总表数据", ProfitAnalysis.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/infor/profitAnalysis/?repage";
    }

}